<template>
  <div>
    <el-card v-if="question">
      <h2>{{ question.title }}</h2>
      <div><b>题目描述：</b>{{ question.description }}</div>
      <div><b>输入格式：</b><pre>{{ question.input_format }}</pre></div>
      <div><b>输出格式：</b><pre>{{ question.output_format }}</pre></div>
      <div><b>样例输入：</b><pre>{{ question.sample_input }}</pre></div>
      <div><b>样例输出：</b><pre>{{ question.sample_output }}</pre></div>
    </el-card>
    <el-divider />
    <MonacoEditor
      v-model:value="code"
      language="python"
      height="400px"
    />
    <el-button type="primary" @click="submitCode" style="margin-top: 16px;">提交评测</el-button>
    <el-divider />
    <div v-if="result">
      <el-alert :title="`评测结果：${result.result}`" :type="result.result === 'Accepted' ? 'success' : 'error'" show-icon />
      <p>得分：{{ result.score }}</p>
      <pre>{{ result.feedback }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import MonacoEditor from '@guolao/vue-monaco-editor'
import axios from 'axios'

const route = useRoute()
const questionId = route.params.questionId || 1 // 支持路由参数或默认1
const question = ref(null)
const code = ref('# 在这里写你的代码')
const result = ref(null)

// 获取题目详情
async function fetchQuestion() {
  const res = await axios.get(`/api/code-questions/${questionId}/`)
  question.value = res.data
  // 可选：自动填充样例代码
  // code.value = res.data.sample_code || '# 在这里写你的代码'
}

onMounted(fetchQuestion)

async function submitCode() {
  try {
    const res = await axios.post('/api/code-submissions/', {
      question: questionId,
      code: code.value
    }, {
      headers: { Authorization: 'Token ' + localStorage.getItem('token') }
    })
    result.value = res.data
  } catch (err) {
    result.value = null
    alert('提交失败: ' + JSON.stringify(err.response?.data || err.message))
    console.error(err)
  }
}
</script>